﻿using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Formats.Asn1;
using System.Globalization;
using System.IO;
using System.IO.Pipes;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static System.Runtime.InteropServices.JavaScript.JSType;

namespace Aribaccio.Office.Demo
{
    public partial class MainWindowModel : ObservableObject
    {
        protected IOfficer Officer { get; set; }
        [ObservableProperty]
        protected int resultSeconds;
        [ObservableProperty]
        protected long resultMilliseconds;

        public MainWindowModel()
        {
            this.Officer = new OfficerCsv();
            this.InitLoaded();
        }

        public void InitLoaded()
        {
            //D:\MyPublishFiles\0508_test_6inch_full_RNDBR066_19_DefectAttributes.csv
            string strFileFullName = @"D:\MyPublishFiles\0508_test_6inch_full_RNDBR066_19_DefectAttributes.csv";

            var data = ReadDataTableAsync(strFileFullName, true, out long milliseconds);

            ResultMilliseconds = milliseconds;

            ResultSeconds = (int)Math.Round(ResultMilliseconds / 1000.0, 0);

        }

        public DataTable ReadDataTableAsync(string argFilePathName, bool argIsExistsColumns, out long milliseconds)
        {
            milliseconds = 0;
            DataTable dtResult = new DataTable();
            OfficerDataTableBatch dtResultBatch = new OfficerDataTableBatch(dtResult);
            Stopwatch swatch = new Stopwatch();
            swatch.Start();
            using (FileStream fileStream = new FileStream(argFilePathName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    //标示列数
                    int nColumnCount = 0;
                    //记录每次读取的一行记录
                    string strLine = "";
                    //读取表头列名
                    if (argIsExistsColumns)
                    {
                        strLine = streamReader.ReadLine();
                        var dataValues = strLine?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (dataValues != null)
                        {
                            nColumnCount = dataValues.Length;
                            foreach (var item in dataValues)
                            {
                                dtResult.Columns.Add(item);
                            }
                        }
                    }                 
                    //读取数据行
                    while ((strLine = streamReader.ReadLine()) != null)
                    {
                        dtResultBatch.AddData(strLine);                                                       
                    }
                    //等待所有任务结束，主线程才退出
                    while (dtResultBatch.HasDataRows) { }              
                }
            }
            swatch.Stop();
            //再更新加载文件时长
            milliseconds = swatch.ElapsedMilliseconds;
            return dtResult;
        }

        public DataTable ReadDataTable(string argFilePathName, bool argIsExistsColumns, out long milliseconds)
        {
            milliseconds = 0;
            Stopwatch swatch = new Stopwatch();
            swatch.Start();
            DataTable fileDataTable = new DataTable();
            //标示第一行列名是否已读取
            bool bIsColumnReader = false;
            //标示列数
            int nColumnCount = 0;
            //记录每次读取的一行记录
            string strLine = "";
            //读取文件数据，写入头部列名及数据
            using (FileStream fileStream = new FileStream(argFilePathName, FileMode.Open, FileAccess.Read))
            {
                using (StreamReader streamReader = new StreamReader(fileStream, Encoding.UTF8))
                {
                    //逐行读取CSV中的数据
                    while ((strLine = streamReader.ReadLine()) != null)
                    {
                        //记录每行记录中的各字段内容（列名、数据）
                        var dataValues = strLine?.Split(new char[] { ',' });
                        if (dataValues == null || dataValues.Length <= 0) continue;
                        if (!bIsColumnReader) { nColumnCount = dataValues.Length; }
                        if (argIsExistsColumns && !bIsColumnReader)
                        {
                            bIsColumnReader = true;
                            foreach (var item in dataValues)
                            {
                                fileDataTable.Columns.Add(item);
                            }
                        }
                        else
                        {
                            if (dataValues.Length > nColumnCount)
                            {
                                var res = dataValues.ToList();
                                res.RemoveRange(nColumnCount, dataValues.Length - nColumnCount);
                                fileDataTable.Rows.Add(res.ToArray());
                            }
                            else
                            {
                                fileDataTable.Rows.Add(dataValues);
                            }
                        }
                    }
                    streamReader.Close();
                    fileStream.Close();
                }
            }
            swatch.Stop();
            //再更新加载文件时长
            milliseconds = swatch.ElapsedMilliseconds;
            return fileDataTable;
        }

        public DataTable ReadDataTablePeek(string argFilePathName, bool argIsExistsColumns, out long resultMilliseconds)
        {
            resultMilliseconds = 0;
            DataTable dtResult = new DataTable();
            Stopwatch swatch = new Stopwatch();
            swatch.Start();
            using (StreamReader streamReader = new StreamReader(argFilePathName, Encoding.UTF8, false))
            {
                int i, m = 0;
                streamReader.Peek();
                var strLine = streamReader.ReadLine();
                var dataValues = strLine?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                if (dataValues != null)
                {
                    foreach (var item in dataValues)
                    {
                        dtResult.Columns.Add(item);
                    }
                }

                while (streamReader.Peek() > 0)
                {
                    m++;
                    strLine = streamReader.ReadLine();
                    if (m >= 1)
                    {
                        dataValues = strLine?.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        if (dataValues == null || dataValues.Length <= 0) continue;
                        dtResult.Rows.Add(dataValues);
                    }
                }
            }
            swatch.Stop();
            //再更新加载文件时长
            resultMilliseconds = swatch.ElapsedMilliseconds;
            return dtResult;
        }


        //public void a()
        //{
        //    using (var reader = new StreamReader(filePath))
        //    using (var csv = new CsvReader(reader, new CsvConfiguration(CultureInfo.InvariantCulture)))
        //    {
        //        csv.Read();
        //        csv.ReadHeader();

        //        var headers = csv.HeaderRecord;
        //        foreach (var header in headers)
        //        {
        //            if (header.ToLower() == "bin" || header.ToLower() == "primarysignal")
        //                resultTable.Columns.Add(new DataColumn(header, typeof(string)));
        //            else
        //                resultTable.Columns.Add(new DataColumn(header, typeof(double)));
        //        }

        //        var batchBuffer = new List<CsvRowData>(batchSize); // 存储当前批次的原始数据和行对象

        //        // while (await csv.ReadAsync())
        //        while (csv.Read())
        //        {
        //            // 主线程中创建行对象（线程安全）
        //            // var row = resultTable.NewRow();

        //            // 复制当前行数据（防止CsvHelper重用数组）
        //            var currentRecord = csv.Context.Parser.Record;// csv.Context.Parser.Record.ToArray();
        //            if (string.IsNullOrEmpty(currentRecord[3]))
        //            {
        //                throw new Exception();
        //            }

        //            // 添加到批次缓冲区
        //            batchBuffer.Add(new CsvRowData
        //            {
        //                Record = currentRecord,
        //                //Row = row
        //            });

        //            // 当批次达到批量大小时，启动处理任务
        //            if (batchBuffer.Count >= batchSize)
        //            {
        //                processingTasks.Add(ProcessBatchAsync(batchBuffer, headers, processedRows, resultTable));
        //                batchBuffer = new List<CsvRowData>(batchSize); // 重置缓冲区
        //            }
        //        }

        //        // 处理剩余的不完整批次
        //        if (batchBuffer.Count > 0)
        //        {
        //            processingTasks.Add(ProcessBatchAsync(batchBuffer, headers, processedRows, resultTable));
        //        }
        //    }

        //    // 5. 等待所有处理任务完成
        //    await Task.WhenAll(processingTasks.ToArray());

        //    // 6. 合并所有行到 DataTable
        //    foreach (var row in processedRows)
        //    {
        //        resultTable.Rows.Add(row);
        //    }

        //    return resultTable;
        //}
    }
}
